<%
  config = field.associated_model_config
  source_abstract_model = RailsAdmin.config(form.object.class).abstract_model

  current_action = params[:action].in?(['create', 'new']) ? 'create' : 'update'

  edit_url = authorized?(:edit, config.abstract_model) ? edit_path(model_name: config.abstract_model.to_param, modal: true, id: '__ID__') : ''

  xhr = !field.associated_collection_cache_all

  collection = xhr ? [[field.formatted_value, field.selected_id]] : controller.list_entries(config, :index, field.associated_collection_scope, false).map { |o| [o.send(field.associated_object_label_method), o.send(field.associated_primary_key).to_s] }

  js_data = {
    xhr: xhr,
    remote_source: index_path(config.abstract_model.to_param, source_object_id: form.object.id, source_abstract_model: source_abstract_model.to_param, associated_collection: field.name, current_action: current_action, compact: true),
    scopeBy: field.dynamic_scope_relationships
  }
%>

<div class="row">
  <div class="col-sm-4">
    <% selected_id = (hdv = field.form_default_value).nil? ? field.selected_id : hdv %>
    <%= form.select field.method_name, collection, { selected: selected_id, include_blank: true }, field.html_attributes.reverse_merge({ data: { filteringselect: true, options: js_data.to_json }, placeholder: t('admin.misc.search') }) %>
  </div>
  <div class="col-sm-8 mt-2 mt-md-0 modal-actions">
    <% if authorized?(:new, config.abstract_model) && field.inline_add %>
      <% path_hash = { model_name: config.abstract_model.to_param, modal: true }.merge!(field.associated_prepopulate_params) %>
      <%= link_to "<i class=\"fas fa-plus\"></i> ".html_safe + wording_for(:link, :new, config.abstract_model), '#', data: { link: new_path(path_hash) }, class: "btn btn-info create" %>
    <% end %>
    <% if edit_url.present? && field.inline_edit %>
      <%= link_to "<i class=\"fas fa-pencil-alt\"></i> ".html_safe + wording_for(:link, :edit, config.abstract_model), '#', data: { link: edit_url }, class: "btn btn-info update ms-2#{' disabled' if field.value.nil?}" %>
    <% end %>
  </div>
</div>